<?php

namespace app\api\controller\app\ldh;

use addons\epay\library\Service;
use app\admin\model\litestore\Litestoregoods;
use app\admin\model\litestore\Litestoreorder;
use app\admin\model\litestore\Litestoreordergoods;
use app\admin\model\Org;
use app\admin\model\Roomclean;
use app\admin\model\Shopcharge;
use app\admin\model\Shopchargeconfig;
use app\admin\model\Shopdevice;
use app\admin\model\Shopdou;
use app\admin\model\Shopmeituan;
use app\admin\model\Shopmno;
use app\admin\model\Shoporder;
use app\admin\model\Shoporderprofit;
use app\admin\model\Shoproom;
use app\admin\model\Shoproombook;
use app\admin\model\Shoproomset;
use app\admin\model\Shoptuan;
use app\admin\model\Userbalance;
use app\admin\model\Userdoucode;
use app\admin\model\Usermeituancode;
use app\admin\model\Userorderprofit;
use app\admin\model\Userscore;
use app\admin\model\Usertuan;
use app\admin\model\Userweixin;
use app\api\service\CfService;
use app\api\service\DouService;
use app\api\service\MtService;
use app\api\service\RoomService;
use app\api\service\VbillService;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use EasyWeChat\Factory;
use fast\Random;
use think\Config;
use think\Validate;
use Yansongda\Pay\Pay;
use function EasyWeChat\Kernel\Support\get_client_ip;

/**
 */
class Order extends Api
{
    protected $noNeedLogin = ['wechatNotify', 'checkOrderBookTime', 'sxfOrderCallback'];
    protected $noNeedRight = '*';

    protected $app = null;

    public function _initialize()
    {
        parent::_initialize();

    }

    public function orderList()
    {

        $page = $this->request->param('page');
        $status = $this->request->param('status');
        $user = $this->auth->getUser();


        $limit = 10;
        $offset = ($page - 1) * $limit;

        $orderModel = new Shoporder();
        $where = array();
        $where['user_id'] = $user['id'];
        if ($status != '') {
            $where['status'] = array('=', $status);
        }
        $list = $orderModel->where($where)->where('status', '<>', 'paying')->order('create_time', 'desc')->limit($offset, $limit)->select();
        foreach ($list as $key => $val) {
            $order_no = $val['order_no'];
            $list[$key]['order_no_str'] = substr($order_no, 0, 5) . "*****" . substr($order_no, strlen($order_no) - 4, 4);
            $list[$key]['book_start'] = date("Y-m-d H:i:s", $val['book_start']);
            $list[$key]['book_end'] = date("Y-m-d H:i:s", $val['book_end']);
            $list[$key]['status_txt'] = $orderModel->formatStatus($val['status']);

        }
        $this->success('', $list);

    }


    public function detail()
    {

        $order_no = $this->request->param("order_no");
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no', $order_no)->find();
        $order['tuan'] = "";
        if ($order['tuan_id'] != -1) {
            $shopTuanModel = new Shoptuan();
            $tuan = $shopTuanModel->where('id', $order['tuan_id'])->find();
            if ($tuan) {
                $order['tuan'] = $tuan['name'];
            }
        }

        $order['status_txt'] = $shopOrderModel->formatStatus($order['status']);
        $order['book_start'] = date("Y-m-d H:i:s", $order['book_start']);
        $order['book_end'] = date("Y-m-d H:i:s", $order['book_end']);
        $this->success('', $order);
    }

    public function orderInit()
    {

        $id = $this->request->param('id');
        $date = $this->request->param('date');
        $startTime = $this->request->param('startTime');
        $hour = $this->request->param('hour');
        $type = $this->request->param('type');
        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $id)->find();
        $tuanId = $this->request->param('tuanId');
        $mtCode = $this->request->param('mtCode');
        $douCode = $this->request->param('douCode');
        $isUseScore = $this->request->param('isUseScore');

        $start = explode("-", $startTime)[0];

        error_log("===start==".$start);
        if ($date == '') {
            $date = date("Y-m-d");
        }

        $startCompareTime = strtotime($date . " " . $start);
        if ($startCompareTime <= time()) {
            $start = date("H:i");
        }
        $day = date("w", time());
        if($day == 0){
            $day = 7;
        }



        $time = array();
        $hourArray = array();
        $roomSet = array();
        $totalPrice = 0;

        $time = getFiveDate();
        foreach ($time as $key => $val) {
            $time[$key]['selected'] = false;
            if ($val['dateValue'] == $date) {
                $time[$key]['selected'] = true;
            }
        }

        if ($type == 0) {
            $hourArray = array();
            for ($i = 0; $i <= 2; $i++) {
                $hourArray[] = $room['min_book_hour'] + $i;
            }
            $totalPrice = $hour * $room['hour_price'];
        } else {
            $totalPrice = $hour * $room['hour_price'];

            $roomSetModel = new Shoproomset();
            $roomSet = $roomSetModel->where('room_id', $id)->order('hour', 'asc')->select();
            foreach ($roomSet as $key => $val) {
                if ($hour == $val['hour']) {
                    $totalPrice = $val['amount'];
                }
            }
        }
        $user = $this->auth->getUser();
        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);

        error_log("===balance===" . $balance);


        $ret = array();
        $ret['name'] = $room['name'];
        $ret['logo'] = cdnurl($room['logo']);
        $ret['date'] = $time;
        $ret['set'] = $roomSet;
        $ret['hours'] = $hourArray;
        $ret['book_hour'] = $hour;
        $ret['balance'] = $balance;

        $ret['startTime'] = $start;
        $ret['book_price'] = $room['hour_price'];
        $min = $hour * 60;
        $d = date("H:i", strtotime("+" . $min . " minute", strtotime($date . " " . $start)));

        $ret['endTime'] = $d;


        $tuanUserModel = new Usertuan();
        $shopTuanModel = new Shoptuan();

        /**
         * 团购券使用价格计算
         */


        if ($tuanId != -1 && $mtCode == '' && $douCode == '') {
            $userTuan = $tuanUserModel->where('id', $tuanId)->find();

            if ($userTuan) {
                error_log("===tuan==2==" . json_encode($userTuan));

                error_log("====statius==".$userTuan['status']."========".$userTuan['valid_time']);

                if ($userTuan['valid_time'] > time() && $userTuan['status'] == 'unuse') {
                    $tuan = $shopTuanModel->where('id', $userTuan['tuan_id'])->find();

                    error_log("====tuan2==".json_encode($tuan));
                    if ($tuan) {
                        $tuanHour = $tuan['hour'];
                        error_log($hour . "==2=====" . $tuanHour);

                        if ($tuanHour >= $hour) {
                            $totalPrice = 0;
                        } else {
                            error_log($hour . "===3====" . $tuanHour);
                            $totalPrice = ($hour - $tuanHour) * $room['hour_price'];
                        }
                    }

                }
            }
        }
        if ($mtCode != '') {
            $userMtCodeModel = new Usermeituancode();
            $shopmeituan = new Shopmeituan();
            $mtCode = $userMtCodeModel->where('mt_code', $mtCode)->find();
            if (!$mtCode) $this->error("此券码不存在");
            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();
                if (!$meituan) $this->error("此券数据不存在");

                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];


                $bookStart = strtotime($date." ". $ret['startTime']);
                $bookEnd = strtotime($date." ". $ret['endTime']);

                $startTime = strtotime($date. " " . $start);
                $endTime = strtotime($date . " " . $end);
                error_log($startTime."=book==2===".$endTime);
                error_log($bookStart."=book==1===".$bookEnd);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if($start =='00:00' && $end =="23:59"){
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);
                error_log($id."=====mt room_id===".json_encode($roomIds));

                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }

                $week = json_decode($meituan['week'],true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }

                error_log($isWeek."=====mt===".$isTime."===2=".$isExist);

                if($isWeek && $isTime && $isExist){
                    if ($meituan['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $meituan['hour']) * $room['hour_price'];
                    }
                }else{

                }



            }

        }
        if ($douCode != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $douCode)->find();
            if (!$douCodeDb) $this->error("此券码不存在");
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];

                error_log("==dou start=".$start);
                error_log("==dou end=".$end);

                error_log($start."=book=star====".$d);


                $bookStart = strtotime($date." ". $ret['startTime']);
                $bookEnd = strtotime($date." ". $ret['endTime']);

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);
                error_log($startTime."=book==2===".$endTime);
                error_log($bookStart."=book==1===".$bookEnd);

                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if($start =='00:00' && $end =="23:59"){
                    $isTime = true;
                }
                $week = json_decode($dou['week'],true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }

                error_log("==isWeek===".$isWeek."=====isTime===".$isTime."====isExist==".$isExist);

                if($isWeek && $isTime && $isExist){
                    if ($dou['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $dou['hour']) * $room['hour_price'];
                    }
                }else{
                    $ret['douCode'] = "";
                }
            }

        }

        if($day == 2){
            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $room['shop_id'])->find();
            $orgId = $shop['org_id'];
            $userChargeModel = new Shopcharge();
            $charge = $userChargeModel->where('user_id',$user['id'])->where('status','payed')->where('org_id',$orgId)->find();
            if($charge){
                $totalPrice = $totalPrice/2;
            }
        }

        $ret['douCode'] = $douCode;

        $ret['total_price'] = round($totalPrice, 2);

        if ($balance >= $totalPrice) {
            $dis_price = $totalPrice;
            $pay_price = 0;
        } else {
            $dis_price = $balance;
            $pay_price = $totalPrice - $balance;
        }
        $ret['pay_price'] = round($pay_price, 2);
        $ret['dis_price'] = round($dis_price, 2);





        /**
         * 判断是和已预定的时间冲突
         */
        $time1 = strtotime($date . " " . $ret['startTime']);
        $time2 = strtotime($date . " " . $ret['endTime']);

        if($time2 <$time1){
           $date2 = date("Y-m-d", strtotime("+1 day",$time1));
           $time2 =strtotime($date2 . " " . $ret['endTime']);
        }

        error_log("====time2===".json_encode($time2));

        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->find();
        $checkEnd = $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->find();
        $checkEnd3= $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->find();


        error_log("===start====" . json_encode($checkStart));
        error_log("===end====" . json_encode($checkEnd));
        error_log("===end2====" . json_encode($checkEnd3));

        $msg = "";
        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {
            $msg = "此时间段已预定";
        }

        /**
         * 团购券检测可用
         */
        $tuanList = $tuanUserModel->checkTuan2($id, $user['id'],$time1,$time2);
        foreach ($tuanList as $key => $val) {
            $tuanList[$key]['end_date'] = date("Y-m-d", strtotime("+" . $val['tuan']['valid_day'] . " day", $val['create_time']));


        }

        /**
         * 积分
         */
        $userScoreModel = new Userscore();
        $in = $userScoreModel->where('user_id',$user['id'])->where('type','in')->where('shop_id',$room['shop_id'])->sum('score');
        $out = $userScoreModel->where('user_id',$user['id'])->where('type','out')->where('shop_id',$room['shop_id'])->sum('score');
        $score = $in-$out;

        if($mtCode == '' && $douCode == '' && $tuanId == -1 && $score >0 && $isUseScore == 1){

            error_log($score."======".$room['book_score']);
            if($score >=$room['book_score'] && $room['book_score'] != 0 && $hour <=4){

                $ret['pay_price'] = 0;
            }
        }

        $ret['tuanList'] = $tuanList;
        $ret['score'] = $score;

        $this->success($msg, $ret);

    }


    public function addBookOrder()
    {
        $id = $this->request->param('id');
        $date = $this->request->param('date');
        $startTime = $this->request->param('startTime');
        $hour = $this->request->param('hour');
        $setId = $this->request->param('setId');//套餐ID 如果ID 为-1 就是时间预定
        $tuanId = $this->request->param('tuanId');
        $mt_code = $this->request->param('mtCode');
        $orgId = $this->request->param('orgId');
        $dou_code = $this->request->param('douCode');
        $user = $this->auth->getUser();
        $isUseScore = $this->request->param('isUseScore');



        $day = date("w", time());
        if($day == 0){
            $day = 7;
        }


        /**
         * 判断是和已预定的时间冲突
         */
        $time1 = strtotime($date . " " . $startTime);


        $min = $hour * 60;

        $endStrotime = strtotime("+" . $min . " minute", strtotime($date . " " . $startTime));

        $time2 = $endStrotime;

        $shopRoomBookModel = new Shoproombook();
        $checkStart = $shopRoomBookModel->where('status','in',['undo','doing'])->where('room_id', $id)->where('start_time', "<=", $time1)->where("end_time", ">=", $time1)->find();
        $checkEnd = $shopRoomBookModel->where('status','in',['undo','doing'])->where('room_id', $id)->where('start_time', "<=", $time2)->where("end_time", ">=", $time2)->find();
        $checkEnd3= $shopRoomBookModel->where('status', 'in', ['undo', 'doing'])->where('room_id', $id)->where('start_time', ">=", $time1)->where("end_time", "<=", $time2)->find();

        error_log("===checkStart===".json_encode($checkStart));
        error_log("===checkEnd===".json_encode($checkEnd));

        if ($checkStart != null || $checkEnd != null || $checkEnd3 != null) {
            $this->error("此时间段预被预定");
        }

        $shopRoomModel = new Shoproom();
        $room = $shopRoomModel->where('id', $id)->find();
        $shopModel = new \app\admin\model\Shop();
        $shop = $shopModel->where('id', $room['shop_id'])->find();

        if($orgId == ""){
            $orgId = $shop['org_id'];
        }



        $orderPrice = 0;
        error_log("======setId====" . $setId);
        if ($setId == -1) {
            $totalPrice = $hour * $room['hour_price'];
            $orderPrice = $totalPrice;
        } else {
            $shopRoomBookSetModel = new Shoproomset();
            $set = $shopRoomBookSetModel->where('id', $setId)->find();
            $totalPrice = $set['amount'];
            $orderPrice = $totalPrice;
        }

        $day = date("w", $time1);
        if($day == 0){
            $day = 7;
        }
        if($day == 2){
            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $room['shop_id'])->find();
            $userChargeModel = new Shopcharge();
            $charge = $userChargeModel->where('user_id',$user['id'])->where('status','payed')->where('shop_id',$shop['id'])->find();
            if($charge){
                $totalPrice = $totalPrice/2;
            }
        }

        error_log("=====totalPrice===" . $totalPrice);
        $user = $this->auth->getUser();
        $userBalanceModel = new Userbalance();
        $balance = $userBalanceModel->balance($room['shop_id'], $user['id']);

        $tuanUserModel = new Usertuan();
        $shopTuanModel = new Shoptuan();
        if ($tuanId != -1 && $mt_code == "" && $dou_code == "") {
            $userTuan = $tuanUserModel->where('user_id', $user['id'])->where('id', $tuanId)->where('status', 'unuse')->order('valid_time', 'asc')->find();
            error_log("==addorder==tuan==".json_encode($userTuan));

            if ($userTuan) {

                error_log($userTuan['status']."==tuan22==".$userTuan['valid_time'] > time());

                if ($userTuan['valid_time'] > time() && $userTuan['status'] == 'unuse') {
                    $tuan = $shopTuanModel->where('id', $userTuan['tuan_id'])->find();

                    error_log("==tuan2==".json_encode($tuan));
                    if ($tuan) {
                        $tuanHour = $tuan['hour'];
                        if ($tuanHour >= $hour) {
                            $totalPrice = 0;
                        } else {
                            $totalPrice = ($hour - $tuanHour) * $room['hour_price'];
                        }
                    }

                }
            }
        }
        $mtService = new MtService();
        $userMtCodeModel = new Usermeituancode();

        if ($mt_code != '') {
            $shopmeituan = new Shopmeituan();
            $mtCode = $userMtCodeModel->where('mt_code', $mt_code)->find();
            if (!$mtCode) $this->error("此券码不存在");
            if ($mtCode['status'] == 'unuse') {
                $meituan = $shopmeituan->where('id', $mtCode['group_id'])->find();
                if (!$meituan) $this->error("此券数据不存在");


                $time = $meituan['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];



                $bookStart = $time1;
                $bookEnd = $time2;

                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);
                $isTime = false;
                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }

                if($start =='00:00' && $end =="23:59"){
                    $isTime = true;
                }

                $roomIds = json_decode($meituan['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $week = json_decode($meituan['week'],true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }

                if($isWeek && $isTime && $isExist){
                    if ($meituan['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $meituan['hour']) * $room['hour_price'];
                    }
                }else{

                }

            }

            //官方校验美团券
            $mtReq = array();
            $mtReq['shop_id'] = $shop['id'];
            $mtReq['code'] = $mt_code;

            $mtInfo = $mtService->couponInfo($mtReq);
            error_log("===mtInfo==" . json_encode($mtInfo));
            if ($mtInfo['code'] != 200) {
                $userMtCodeModel->where('mt_code', $mtCode)->update(['status' => 'bad']);
                $this->error("此券不用");
            }
        }

        $douVerifyToken = "";
        if ($dou_code != '') {
            $userDouCodeModel = new Userdoucode();
            $shopDouModel = new Shopdou();
            $douCodeDb = $userDouCodeModel->where('dou_code', $dou_code)->find();
            if (!$douCodeDb) $this->error("此券码不存在");
            if ($douCodeDb['status'] == 'unuse') {
                $dou = $shopDouModel->where('sku_id', $douCodeDb['sku_id'])->find();
                if (!$dou) $this->error("此券数据不存在");
                $roomIds = json_decode($dou['room_id'], true);
                $isExist = false;
                foreach ($roomIds as $key => $val) {
                    if ($id == $val) {
                        $isExist = true;
                    }
                }
                $time = $dou['use_time'];
                $start = explode("~", $time)[0];
                $end = explode("~", $time)[1];



                $bookStart = $time1;
                $bookEnd = $time2;


                $startTime = strtotime($date . " " . $start);
                $endTime = strtotime($date . " " . $end);


                error_log($startTime."=book==2===".$endTime);
                error_log($bookStart."=book==1===".$bookEnd);

                $isTime = false;


                if ($bookStart >= $startTime && $bookEnd <= $endTime) {
                    $isTime = true;
                }
                if($start =='00:00' && $end =="23:59"){
                    $isTime = true;
                }

                $week = json_decode($dou['week'],true);
                $isWeek = false;
                foreach ($week as $k2 => $v2) {
                    if ($v2 == $day) {
                        $isWeek = true;
                        break;
                    }
                }

                error_log("==week===".$isWeek."===time==".$isTime."==exisit====".$isExist);

                if($isWeek && $isTime && $isExist){


                    $douService = new DouService();
                    $douVerifyToken = $douService->checkCode($dou_code);
                    if($douVerifyToken== ''){
                        $this->error("此券为无效券");
                    }
                    if ($dou['hour'] >= $hour) {
                        $totalPrice = 0;
                    } else {
                        $totalPrice = ($hour - $dou['hour']) * $room['hour_price'];
                    }

                }else{
                    $this->error("此券不能可用");
                }
            }

        }


        $pay_price = $totalPrice;
        $type = "";
        $dis_price = 0;

        if ($totalPrice > 0) {
            if ($balance > 0 && $mt_code == "" && $dou_code == "") {
                $type = "balance";
                if ($balance >= $totalPrice) {
                    $dis_price = $totalPrice;
                    $pay_price = 0;
                } else {
                    $dis_price = $balance;
                    $pay_price = $totalPrice - $balance;
                }

            }
        }

        /**
         * 积分
         */
        $userScoreModel = new Userscore();
        $in = $userScoreModel->where('user_id',$user['id'])->where('type','in')->where('shop_id',$shop['id'])->sum('score');
        $out = $userScoreModel->where('user_id',$user['id'])->where('type','out')->where('shop_id',$shop['id'])->sum('score');
        $score = $in-$out;
        $orderNo = getOrderSn();
        $db = array();
        if($mt_code == '' && $dou_code == '' && $tuanId == -1 && $score >0 && $isUseScore == 1){

            error_log($score."======".$room['book_score']);
            if($score >=$room['book_score'] && $room['book_score'] != 0 && $hour <=4    ){
                $pay_price = 0;
                $db['score'] = $room['book_score'];
            }
        }


        $db['shop_id'] = $shop['id'];
        $db['shop_name'] = $shop['name'];
        $db['room_id'] = $room['id'];
        $db['room_name'] = $room['name'];
        $db['user_id'] = $user['id'];
        $db['order_no'] = $orderNo;
        $db['create_time'] = time();
        $db['update_time'] = time();
        $db['amount'] = $orderPrice;
        $db['pay_amount'] = $pay_price;
        $db['book_start'] = $time1;
        $db['book_end'] = $time2;
        $db['set_id'] = $setId;
        $db['tuan_id'] = $tuanId;
        $db['balance'] = $dis_price;
        $db['mt_code'] = $mt_code;
        $db['dou_code'] = $dou_code;
        $db['dou_token'] = $douVerifyToken;
        $db['org_id'] = $orgId;
        $db['pay_rate'] = formatMoney($shop['pay_rate'] * $db['pay_amount'] / 100);
        $db['rate'] = formatMoney($shop['ratio'] * $db['pay_amount'] / 100);


        $code = mt_rand(100000, 999999);
        $db['open_code'] = $code;

        $shopOrderModel = new Shoporder();
        $id = $shopOrderModel->insertGetId($db);
        if ($id > 0) {

            if ($mt_code != "") {
                $userMtCodeModel->where('mt_code', $mtCode)->update(['status' => 'lock']);
            }
            if ($dou_code != "") {

                $userDouCodeModel->where('dou_code', $dou_code)->update(['status' => 'lock', 'order_id' => $id]);
            }

            $info = array();
            if ($pay_price > 0) {
                $userwxModel = new Userweixin();
                $wx = $userwxModel->where('user_id', $user['id'])->find();
//                $params = [
//                    'out_trade_no' => $orderNo,//你的订单号
//                    'total_fee' => $pay_price * 100,//单位元
//                    'body' => $shop['name'] . "预定" . $hour . "小时",
//                    'openid' => $wx['openid'],
//
//                ];
//                $config = Service::getConfig("wechat");
//                $config['notify_url'] = $url;
//                $pay = Pay::wechat($config);
//                $result = $pay->miniapp($params);

                $url = 'https://' . $_SERVER['HTTP_HOST'] . "/api/app/ldh/order/sxfOrderCallback";

                $orgModel = new Org();
                $org = $orgModel->where('id', $orgId)->find();


                $orgModel = new Org();
                $org = $orgModel->where('id', $orgId)->find();
                $shopMnoModel =new Shopmno();
                $shopMno = $shopMnoModel->where('shop_id',$shop['id'])->find();
                $mno = $org['mno'];
                if($shopMno){
                    if($shopMno['ratio'] == 100){
                        //走挂靠
                        $mno = $shopMno['mno'];
                    }else{
                        //走分账
                        $fusruleId = array();
                        $fusruleId['mno'] = $shopMno['mno'];

                        $realPay = formatMoney($pay_price- $pay_price*0.006);
                        $fusruleId['allotValue'] = formatMoney($shopMno['ratio']*$realPay/100);

                        $fs = array();
                        $fs[] = $fusruleId;
                        $req['fusruleId'] = $fs;
                    }
                }

                $req['mno'] = $mno;//纷享未来药房
                $req['ordNo'] = $orderNo;
                $req['amt'] = formatMoney($pay_price);

                $req['payType'] = "WECHAT";
                $req['payWay'] = "03";
                $req['subAppid'] = $org['app_id'];
                $req['userId'] = $wx['openid'];

                $req['subject'] = "包厢预定";
                $req['tradeSource'] = "01";
                $req['trmIp'] = get_client_ip();
                $req['notifyUrl'] = $url;

                error_log("=====ret===".json_encode($req));

                $vbillService = new VbillService();
                $res = $vbillService->jsApi($req);
                error_log("===res===".json_encode($res));
                $result = json_decode($res, true);
                $bizCode = $result['respData']['bizCode'];
                $bizMsg = $result['respData']['bizMsg'];

                error_log("==sxfPay======" . json_encode($result));
                if ($bizCode == '0000') {
                    $info['order_no'] = $orderNo;
                    $info['payInfo'] = $result['respData'];
                } else {
                    $this->error($bizMsg);
                }
            } else {

                $info['order_no'] = $orderNo;
                $info['payInfo'] = "";

                if ($tuanId != -1) {
                    $tuanUserModel->where('id', $tuanId)->update(['status' => 'used']);
                }

                $order = $shopOrderModel->where('id', $id)->find();

                if ($mt_code != "") {
                    $isChecked =  $mtService->syncMt($order);
                    if($isChecked == 0) $this->error("验券失败，请联系商家");
                }

                if($dou_code != ""){
                    $douService = new DouService();
                    $isChecked =  $douService->verifyCode($order);
                    if($isChecked == 0) $this->error("验券失败，请联系商家");

                }

                if($order['score'] >0){
                    $userScoreModel->insert(['user_id'=>$user['id'],'type'=>'out','mark'=>$room['name']."预定抵扣",
                        'score'=>$order['score'],'create_time'=>time(),'order_id'=>$order['id'],'shop_id'=>$order['shop_id']]);
                }

                $this->redis->set($order['shop_id'], time());
                $roomService = new RoomService();
                $roomService->addBookData($order);
                $shopOrderModel->where('id', $id)->update(['status' => 'payed', 'update_time' => time()]);



            }



            if ($type == "balance") {

                $userBalanceModel = new Userbalance();
                $userBalanceModel->insert(['user_id' => $user['id'], 'type' => 'out',
                    'amount' => $dis_price, 'mark' => $shop['name'] . '预定抵扣', 'create_time' => time(), 'shop_id' => $shop['id'], 'order_id' => $id]);
            }




            $this->success('下单成功', $info);
        } else {
            $this->error("订单生成失败,请联系客服");
        }

    }

    public function restore()
    {
        $user = $this->auth->getUser();
        $order_no = $this->request->param('order_no');
        $shopOrderModel = new Shoporder();
        $userBalanceModel = new Userbalance();
        $userTuanModel = new Usertuan();
        $order = $shopOrderModel->where('order_no', $order_no)->find();
        if ($order) {
            if ($order['user_id'] != $user['id']) {
                $this->error("无权限操作");
            }
            if ($order['status'] == 'paying') {
                $b = $userBalanceModel->where('user_id', $user['id'])->where('type', 'out')->where('order_id', $order['id'])->find();
                if ($b) {
                    if ($order['tuan_id'] != -1) {
                        $tuan = $userTuanModel->where('id', $order['tuan_id'])->find();
                        if ($tuan) {
                            $userTuanModel->where('id', $tuan['id'])->update(['status' => 'unuse']);
                        }
                    }
                    $userScoreModel =  new Userscore();
                    if($order['score'] >0){
                        $userScoreModel->insert(['user_id'=>$order['user_id'],'type'=>'in','mark'=>'积分返还',
                            'score'=>$order['score'],'create_time'=>time(),'order_id'=>$order['id'],'shop_id'=>$order['shop_id']]);
                    }

                    if ($order['mt_code'] != "") {
                        $userMtModel = new Usermeituancode();
                        $userMtModel->where('mt_code', $order['mt_code'])->update(['status' => 'unuse']);

                    }
                    if ($order['dou_code'] != "") {
                        $userDouModel = new Userdoucode();
                        $userDouModel->where('dou_code', $order['dou_code'])->update(['status' => 'unuse']);

                    }
                    $userBalanceModel->where('id', $b['id'])->delete();
                    $this->success('');
                } else {
                    $this->success('');
                }
            } else {
                $this->error("订单不允许");
            }
        } else {
            $this->error("订单不存在");
        }
    }

    public function sxfOrderCallback()
    {
        $param = file_get_contents("php://input");
        error_log("===order===callback=====" . json_encode($param));

        $ret = json_decode($param, true);
        $amt = $ret['amt'];
        $out_trade_no = $ret['ordNo'];
        $transactionId = $ret['transactionId'];
        if ($ret['bizCode'] == '0000') {

            $back = array();
            $back['code'] = "success";
            $back['msg'] = "成功";
            echo json_encode($back);


            $shopOrderModel = new Shoporder();
            $order = $shopOrderModel->where('order_no', $out_trade_no)->find();
            $shopOrderModel->where('id', $order['id'])->update(['status' => 'payed', 'update_time' => time()]);


            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $order['shop_id'])->find();

            /**
             * 商家分润
             */
            $shopOrderProfitModel = new Shoporderprofit();
            $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                'user_id' => $shop['user_id'], 'create_time' => time(), 'amount' => formatMoney(($order['pay_amount'] - $order['rate'] - $order['pay_rate']))]);

            /**
             * 代理商分润
             */
            if ($shop['agent_ratio'] > 0) {

                $userOrderProfitModel = new Userorderprofit();

                $agentFee = $shop['agent_ratio'] * $order['pay_amount'] / 100;

                if ($agentFee > 0) {
                    $userOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                        'user_id' => $shop['agent_id'], 'create_time' => time(), 'amount' => formatMoney($agentFee)]);
                }

            }


            $this->redis->set($order['shop_id'], time());


            $roomService = new RoomService();
            $roomService->addBookData($order);

            //余额添加
                $room_id = $order['room_id'];
                $shopRoomModel = new Shoproom();
                $room = $shopRoomModel->where('id',$room_id)->find();
                $userScoreModel =  new Userscore();
                $diff =   $order['book_end'] - $order['book_start'];
                $hour = floor($diff / (60 * 60));
                if($room['back_score'] >0 && $hour>=4){
                    $userScoreModel->insert(['user_id'=>$order['user_id'],'type'=>'in','mark'=>$order['room_name']."预定返积分",
                        'score'=>$room['back_score'],'create_time'=>time(),'order_id'=>$order['id'],'shop_id'=>$order['shop_id']]);
                }





            if ($order['tuan_id'] != -1) {
                $tuanUserModel = new Usertuan();
                $tuanUserModel->where('id', $order['tuan_id'])->update(['status' => 'used']);

            }
            if ($order['mt_code'] != "") {
                $mtService = new MtService();
                $mtService->syncMt($order);
            }
            if ($order['dou_code'] != "") {
                $userDouModel = new Userdoucode();
                $userDouModel->where('dou_code', $order['dou_code'])->update(['status' => 'unuse']);

            }




        }
    }

    public function wechatNotify()
    {

        $config = Service::getConfig('wechat');
        $pay = Pay::wechat($config);
        $result = $pay->verify();

        $out_trade_no = $result['out_trade_no'];
        $amount = $result['total_fee'] / 100;


        if (in_array($result['return_code'], ['SUCCESS'])) {

            $shopOrderModel = new Shoporder();
            $order = $shopOrderModel->where('order_no', $out_trade_no)->find();
            $shopOrderModel->where('id', $order['id'])->update(['status' => 'payed', 'update_time' => time()]);


            $shopModel = new \app\admin\model\Shop();
            $shop = $shopModel->where('id', $order['shop_id'])->find();

            /**
             * 商家分润
             */
            $shopOrderProfitModel = new Shoporderprofit();
            $shopOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                'user_id' => $shop['user_id'], 'create_time' => time(), 'amount' => formatMoney(($order['pay_amount'] - $order['rate'] - $order['pay_rate']))]);

            /**
             * 代理商分润
             */
            if ($shop['agent_ratio'] > 0) {

                $userOrderProfitModel = new Userorderprofit();

                $agentFee = $shop['agent_ratio'] * $order['pay_amount'] / 100;

                if ($agentFee > 0) {
                    $userOrderProfitModel->insert(['order_id' => $order['id'], 'shop_id' => $order['shop_id'], 'type' => 'order',
                        'user_id' => $shop['agent_id'], 'create_time' => time(), 'amount' => formatMoney($agentFee)]);
                }

            }


            $this->redis->set($order['shop_id'], time());


            $roomService = new RoomService();
            $roomService->addBookData($order);


            if ($order['tuan_id'] != -1) {
                $tuanUserModel = new Usertuan();
                $tuanUserModel->where('id', $order['tuan_id'])->update(['status' => 'used']);

            }
            if ($order['mt_code'] != "") {
                $mtService = new MtService();
                $mtService->syncMt($order);
            }

            if ($order['dou_code'] != "") {
                $userDouModel = new Userdoucode();
                $userDouModel->where('dou_code', $order['dou_code'])->update(['status' => 'unuse']);

            }


        }
        return $pay->success();
    }


    public function checkOrderBookTime()
    {

        $date = $this->request->param('date');
        $hour = $this->request->param('hour');
        $bookStart = $this->request->param('starTime');
        $room_id = $this->request->param('room_id');

        $bookStartTime = strtotime($date . " " . $bookStart);
        $bookEndTime = strtotime("+" . $hour * 60 . " minute", strtotime($date . " " . $bookStart));

        $dateTime = strtotime($date);

        $ret = array();
        $oneTime = strtotime("+1 day", $dateTime);
        $date2 = date("Y-m-d", $oneTime);


        $oneInitStart = $date . " 00:00";
        $oneInitStart2 = date("Y-m-d", $oneTime) . " 00:00";

        $shopBookTime = new Shoproombook();
        $bookList = $shopBookTime->where('room_id', $room_id)->where('status', "<>", 'done')->select();

        $oneList = array();
        $ret = array();
        $twoList = array();
        for ($i = 0; $i <= 23; $i++) {

            $obj = array();
            $obj['isFree'] = true;
            $obj['isNow'] = false;
            $obj['index'] = $i;

            $obj2 = array();
            $obj2['isFree'] = true;
            $obj2['isNow'] = false;
            $obj2['index'] = $i;
            $startTime = strtotime("+" . $i . " hour", strtotime($oneInitStart));
            if ($i != 23) {
                $endTime = strtotime("+" . ($i + 1) . " hour", strtotime($oneInitStart));
            } else {
                $endTime = strtotime($date . " 23:59:59");
            }

            $startTime2 = strtotime("+" . $i . " hour", strtotime($oneInitStart2));
            if ($i != 23) {
                $endTime2 = strtotime("+" . ($i + 1) . " hour", strtotime($oneInitStart2));
            } else {
                $endTime2 = strtotime($date2 . " 23:59:59");
            }

            foreach ($bookList as $k => $v) {
                if (($startTime >= $v['start_time'] && $endTime <= $v['end_time']) || ($v['end_time'] >= $startTime && $v['end_time'] <= $endTime) || ($v['start_time'] >= $startTime && $v['start_time'] <= $endTime)) {
                    $obj['isFree'] = false;
                }

                if (($startTime2 >= $v['start_time'] && $endTime2 <= $v['end_time']) || ($v['end_time'] >= $startTime2 && $v['end_time'] <= $endTime2) || ($v['start_time'] >= $startTime2 && $v['start_time'] <= $endTime2)) {
                    $obj2['isFree'] = false;
                }
            }

            if (($startTime >= $bookStartTime && $endTime <= $bookEndTime) || ($bookEndTime > $startTime && $bookEndTime <= $endTime) || ($bookStartTime > $startTime && $bookStartTime <= $endTime)) {
                if ($obj['isFree'] == true) {
                    $obj['isNow'] = true;
                }

            }

            if (($startTime2 >= $bookStartTime && $endTime2 <= $bookEndTime) || ($bookEndTime >= $startTime2 && $bookEndTime <= $endTime2) || ($bookStartTime >= $startTime2 && $bookStartTime <= $endTime2)) {
                if ($obj2['isFree'] == true) {
                    $obj2['isNow'] = true;
                }
            }
            $oneList[] = $obj;
            $twoList[] = $obj2;

        }
        $ret['list'] = $oneList;
        $ret['date'] = $date;
        $ret['date2'] = date("Y-m-d", $oneTime);
        $ret['list2'] = $twoList;


        $this->success('', $ret);
    }


    public function refund(){

        $order_no = $this->request->param('order_no');
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no',$order_no)->find();
        if($order['status'] != "payed"){
            $this->error("此订单状态不允许退款");
        }

        $orgModel = new Org();
        $org = $orgModel->where('id',$order['org_id'])->find();
        $hour = $org['refund_hour'];
        $time = strtotime(  "+".$hour." hour",time());
        if($time >= $order['book_start']){
            $this->error("离开始只有".$hour."个小时，不允许退款");
        }
        $amount = $order['pay_amount'];

        $shopModel = new \app\admin\model\Shop();

        $shop = $shopModel->where('id',$order['shop_id'])->find();
        if($order['balance']>=$amount){
            $refundAmount = 0;
            $backBalanceAmount = $amount;
        }else{
            $refundAmount = $amount-$order['balance'];
            $backBalanceAmount = $order['balance'];
        }

        if($order['pay_amount'] >0 && $refundAmount>0){


            $refundOrder_no = getOrderSn();
            $orderParam = [
                'out_trade_no' => $order['order_no'],
                'out_refund_no' => $refundOrder_no,
                'total_fee' => $order['pay_amount'] * 100,
                'refund_fee' => $refundAmount* 100,
                'refund_desc' => '预定退款',
            ];



            $orgModel = new Org();
            $org = $orgModel->where('id',$order['org_id'])->find();
            $req = array();
            $req['mno']= $org['mno'];
            $req['ordNo']= $refundOrder_no;
            $req['origOrderNo']= $order['order_no'];
            $req['amt']=$refundAmount;

            $vbillService = new VbillService();
            $ret = $vbillService->refund($req);
            $result = json_decode($ret,true);
            if($result['respData']['bizCode'] != "0000"){
                $this->error($result['respData']['bizMsg']);
            }
            $shopOrderModel->where('id',$order['id'])->update(['status'=>'refund','refund_order_no'=>$refundOrder_no]);
        }else{
            $shopOrderModel->where('id',$order['id'])->update(['status'=>'refund']);
        }
        //退余额
        if($order['balance'] >0){
            $userBalanceModel = new Userbalance();
            $balanceDb = $userBalanceModel->where('user_id',$order['user_id'])->where('order_id',$order['id'])->where('type','out')->find();
            $userBalanceModel->insert(['user_id'=>$balanceDb['user_id'],'type'=>'in','amount'=>$balanceDb['amount'],'mark'=>'订单退款','create_time'=>time(),
                'shop_id'=>$balanceDb['shop_id'],'order_id'=>$balanceDb['order_id'],'b_type'=>'refund']);
        }
        //退商家分润 ，代理商分润
        if($order['pay_amount'] >0){
            $shopOrderProfitModel =new Shoporderprofit();
            $shopOrderProfitModel->where('order_id',$order['id'])->where('user_id',$shop['user_id'])->delete();

            $userOrderProfitModel = new Userorderprofit();
            $userOrderProfitModel->where('user_id',$shop['agent_id'])->where('order_id',$order['id'])->delete();
        }

        //团购券
        if($order['tuan_id'] != -1){
            $userTuanModel = new Usertuan();
            $userTuanModel->where('order_id',$order['id'])->update(['status'=>'unuse']);
        }

        //恢复预定
        $roomBookOrderModel = new Shoproombook();
        $roomBookOrderModel->where('order_id',$order['id'])->delete();

        $cleanRoomModel = new Roomclean();
        $cleanRoomModel->where('order_id',$order['id'])->delete();


        $this->success('退款成功');


    }

    public function leave(){
        $order_no = $this->request->param('order_no');
        $shopOrderModel = new Shoporder();
        $order = $shopOrderModel->where('order_no',$order_no)->find();
        if($order['status'] == "paying"  || $order['status'] == 'done' || $order['status'] == "refund" ){
            $this->error("此订单状态不允许离店操作");
        }

        $end = $order['book_end'];
        $hour=floor(($end-time())%86400/3600);

        $bookHour=floor(($end-$order['book_start'])%86400/3600);
        $bookHour = ceil($bookHour);
        $payAmount = $order['pay_amount'];
        $price = $payAmount/$bookHour;
        if($hour >=1){
            $hour = floor($hour);
            $payAmount = formatMoney($price*$hour);


            $refundOrder_no = getOrderSn();
            $orderParam = [
                'out_trade_no' => $order['order_no'],
                'out_refund_no' => $refundOrder_no,
                'total_fee' => $order['pay_amount'] * 100,
                'refund_fee' => $payAmount* 100,
                'refund_desc' => '离店退款',
            ];



            $orgModel = new Org();
            $org = $orgModel->where('id',$order['org_id'])->find();
            $req = array();
            $req['mno']= $org['mno'];
            $req['ordNo']= $refundOrder_no;
            $req['origOrderNo']= $order['order_no'];
            $req['amt']=$payAmount;

            $vbillService = new VbillService();
            $ret = $vbillService->refund($req);
            $result = json_decode($ret,true);
            if($result['respData']['bizCode'] != "0000"){
                $this->error($result['respData']['bizMsg']);
            }

            $shopOrderModel->where('id',$order['id'])->update(['status'=>'done']);
            $shopBookOrderModel = new Shoproombook();
            $shopBookOrderModel->where('order_id',$order['id'])->update(['status'=>'done']);
            $shopRoomModel = new Shoproom();
            $shopRoomModel->where('id',$order['room_id'])->update(['is_clean'=>-1]);


            $shopDeviceModel = new Shopdevice();
            $device = $shopDeviceModel->where('room_id',$order['room_id'])->find();
            $sn = $device['sn'];
            $req = array();
            $req['sec'] = 0;
            $req['orderNo'] = $order_no;
            $req['sn'] = $sn;


            $ret = http_post_json($this->openCmdUrl, json_encode($req));
            $ret = json_decode($ret, true);

        }

        $this->success('成功');

    }


}
